const express = require("express");
const multiparty = require('multiparty')
const path = require('path')

const BlogService =  require("../services/blog-services")
const LeacotsService =  require("../services/leacots-services")
const JSONResult =  require("../bean/json-result")
const {timeFormat} =  require("../utils/date-utils")


const router = express.Router()

const services = new BlogService()
const leacotsServices = new LeacotsService()

/**
 * 页面底部个人信息
 * @type {{QQ: string, phone: string, email: string}}
 */
const info = {
    phone:"18393106332",
    QQ:"1270417842",
    email:"1270417842@qq.com"
}
/**
 * 主页:文章列表页面
 */
router.get('/home.html',async (req,res,next) =>{
    console.log("homeController ========== req.url:", req.url)
    // const {query:{category,page}} = req.url
    const options = {
        category:"最新文章"
    }
    const values = await services.getArticlesList(1,20,options)
    console.log("values:",values)
    res.render('blog/home.html',{title:"最新文章",articleList:values,info:info});
})

/**
 * 新增文章页面
 */
router.get("/add-article.html",async(req,res,next) =>{
    const RowsDataPackets = await services.queryCategoryList()
    console.log("controller===queryCategoryList:====",RowsDataPackets)
    res.render('blog/add-article.html',{title:"新增文章",info:info,categoryList:RowsDataPackets});
})
/**
 * 新增文章接口
 */
router.post("/add-article.do",async (req,res,next) =>{
    const {query,params,body,path,session:{user:{userId}}} = req
    const {title,content,description,categoryId} = body
    console.log("controller============add-article=========categoryId:",categoryId)
    const article = {
        title:title,
        content:content,
        description:description,
        isPublished:true,                 //'公开或私密',
        isRecommend:true,                 // '推荐开关',
        isAppreciation:true,              //'赞赏开关',
        createTime:timeFormat(new Date()),//'创建时间',
        categoryId:categoryId,                     //'文章分类category_id',
        userId:userId,                    //'文章作者id',
        isTop:0,                          //'是否置顶',
    }
    const OkPacket = await services.insertOneArticle(article)
    console.log("controller ==== OkPacket:",OkPacket)
    const {insertId,affectedRows} = OkPacket
    console.log("controller ==== insertId:",insertId)
    console.log("controller ==== affectedRows:",affectedRows)
    res.json(new JSONResult({code:200,message:"新增文章成功！！",data:{id:insertId}}))
    next()
})

/**
 * 文章详情页面
 */
router.get("/details.html/:id",async (req,res,next) =>{
    // const {params:{id}} = req
    const {path,query,params:{id},hostname} = req
    const article = await services.getArticleById(id)
    console.log("controller====article:",article)
    res.render('blog/details.html',{title:"文章详情",article:article[0],info:info});
})

/**
 * 编辑文章页面
 */
router.get("/edit-article.html/:id",async (req,res,next) =>{
    const {params:{id}} = req
    const RowsDataPacket = await services.getArticleById(id)
    console.log("controller=====article:",RowsDataPacket)
    const RowsDataPackets = await services.queryCategoryList()
    res.render('blog/edit-article.html',{title:"编辑文章",article:RowsDataPacket[0],info:info,categoryList:RowsDataPackets});
})

/**
 * 编辑文章接口
 */
router.post("/edit-article.do/:articleId",async (req,res,next) =>{
    const {path,params:{articleId},query,body} = req
    const {title,content,description,updateTime,categoryId,userId} = body
    const article = {
        id:articleId,//主键
        title:title,//'文章标题',
        content:content, //'文章正文',
        description:description,//'描述',
        updateTime:timeFormat(new Date()),//'更新时间',
        categoryId:categoryId,//'文章分类category_id',
        userId:userId//'文章作者',
    }
    console.log("article:",article)
    const OkPacket = await services.updateOneArticle(article)
    console.log("controller===========OkPacket:",OkPacket)
    const { affectedRows,message} = OkPacket
    if (OkPacket) {
        console.log("OkPacket. affectedRows:", affectedRows)
        console.log("OkPacket.message:",message)
        res.json(new JSONResult({code:200,message:"编辑文章成功！！",data:{}}))
    } else {
        res.json(new JSONResult({code:200,message:"编辑失败，重新编辑！",data:{}}))
    }
})

/**
 * 删除文章接口
 */
router.post("/delete-article.do/:articleId",(req,res,next) =>{
    const {path,params:{articleId},query,body} = req
    const {id,title,content,description,updateTime,categoryId,userId} = body
    const article = {
        id:id,//主键
        title:title,//'文章标题',
        content:content, //'文章正文',
        description:description,//'描述',
        updateTime:updateTime || new Date().toLocaleDateString()(),//'更新时间',
        categoryId:categoryId,//'文章分类category_id',
        userId:userId//'文章作者',
    }
    const dataset = services.deleteArticleById(articleId)
    if (dataset) {
        res.json(new JSONResult({code:200,message:"删除成功！",data:{}}))
    } else {
        res.json(new JSONResult({code:200,message:"删除失败！",data:{}}))
    }
})

/**
 * 微语
 */
router.get('/whisper.html',async (req,res,next) =>{
    res.render('blog/whisper.html',{title:"微语",info:info});
})

/**
 * 留言页面
 */
router.get('/leacots.html',async (req,res,next) =>{
    const RowsDataPacket = await leacotsServices.getLeacotsList(1,40)
    console.log("controller=====leacots====RowsDataPacket:",RowsDataPacket)
    const count = Array.isArray(RowsDataPacket) ? RowsDataPacket.length :0
    res.render('blog/leacots.html',{title:"留言",leacotsList:RowsDataPacket,info:info,count:count});
    next()
})

/**
 * 新增留言接口
 */
router.post('/add-leacots.do', async (req,res,next) =>{
    const {query,params,body,path,session:{user:{userId}}} = req
    const {content,createTime} = body
    const time = timeFormat(createTime)
    const leacots = {
        content:content,//留言内容
        createTime:time,//'留言时间',
        categoryId:"",  //'文章分类category_id',
        userId:userId,  //留言人id,
    }
    console.log("leacots:",leacots)
    const OkPacket = await leacotsServices.insertLeacots(leacots)
    console.log("----controller----createLeacots-----result:",OkPacket)
    let json = null
    if (OkPacket) {
        const {insertId,affectedRows} = OkPacket
        console.info(`数据库留言新增成功${affectedRows}条！`)
        json = new JSONResult({code:200,message:"留言成功！",data:{id:insertId}})
    } else {
        json = new JSONResult({code:404,message:"留言失败！",data:{}})
    }
    res.json(json)
    next()
})
/**
 * 更新留言接口
 */
router.put('/update-leacots.do', async (req,res,next) =>{
    const {query,params,body,path,session:{user}} = req
    const {id,content,createTime} = body
    const time = timeFormat(createTime)
    const leacots = {
        id:id,                //留言id
        content:content,      //留言内容
        createTime:time,      //'创建时间',
        categoryId:"",        //'留言分类category_id',
        userId:user.userId,       //'留言人',
    }
    const OkPacket = await leacotsServices.updateLeacots(leacots)
    console.log(`---controller---updateLeacots---result:`,OkPacket)
    let json = null
    if (OkPacket) {
        const {affectedRows} = OkPacket
        console.info(`数据库修改留言成功${affectedRows}行！`)
        json = new JSONResult({code:200,message:"更新留言成功！",data:{}})
    } else {
        json = new JSONResult({code:404,message:"更新留言失败！",data:{}})
    }

    res.json(json)
    next()
})

/**
 * 关于页面
 */
router.get('/about.html',async (req,res,next) =>{
    const {session:{user:{userId,nickname,avatar,age}}} = req
    const skills = [
        {id:0,label:"PS",logo:"logo-ps.jpg",level:20},
        {id:1,label:"HTML",logo:"logo-html.png",level:90},
        {id:2,label:"CSS",logo:"logo-css.png",level:90},
        {id:3,label:"JavaScript",logo:"logo-js.png",level:90},
        {id:4,label:"VUE",logo:"logo-vue.png",level:90},
        {id:5,label:"React",logo:"logo-react.svg",level:50},
        {id:6,label:"Node",logo:"logo-node.svg",level:50},
        {id:7,label:"Webpack",logo:"logo-webpack.png",level:50},
        {id:8,label:"MySQL",logo:"logo-mysql.svg",level:50},
        {id:9,label:"Swagger",logo:"logo-swagger.png",level:70},
        {id:10,label:"Spring",logo:"logo-spring.png",level:30},
        {id:11,label:"MyBatis",logo:"logo-mybatis.png",level:30},
        {id:12,label:"Git",logo:"logo-git.png",level:70},
        {id:13,label:"Redis",logo:"logo-redis.jpg",level:5},
        {id:14,label:"Hibernate",logo:"logo-hibernate.svg",level:5},
        {id:15,label:"Maven",logo:"logo-maven.png",level:80},
        {id:16,label:"Linux",logo:"logo-linux.jpg",level:5},
        {id:16,label:"Docker",logo:"logo-docker.jpg",level:0},
    ]

    const personalInfo = {
        name:nickname,
        age:25,
        career:"前端开发工程师",
        interest:"爱好吃饭，睡觉，打豆豆，交友，写作，看电影，敲代码。",
        motto:"我不管古今世事，愿永为天地闲人。"
    }

    res.render('blog/about.html',{title:"关于",skills:skills,personalInfo:personalInfo,info:info});
})

/**
 * 图片文件上传
 */
router.post('/upload/images',(req,res,next) =>{
    // 上传的文件在req.files中
    // const filename = req.files[0].path + path.parse(req.files[0].originalname).ext
    // console.log(filename);
    console.log("============进入后台文件上传接口================")
    //获取表单的数据 以及post过来的图片
    const form = new multiparty.Form({
        encoding:"utf-8",
        uploadDir:"./public/static/images/",  //文件上传地址
        keepExtensions:true  //保留后缀
    })
    // 上传图片保存的地址     目录必须存在
    form.uploadDir = "./public/static/images/"
    form.parse(req,(err,fields,files)=>{
        /**获取提交的数据以及图片上传成功返回的图片信息*/
        /**获取表单的数据*/
        console.log("上传文件表单数据：",fields);
        /**图片上传成功返回的信息*/
        console.log("上传的文件：",files);
        const {image} = files
        let imgUrl = image[0].path
        console.log("imgUrl:",imgUrl)
        imgUrl = imgUrl.replace("public",'')
        // 拿到的是 提交的数据 和图片 路径 保存到数据库表中
        res.send(new JSONResult({code:200,message:"上传成功",data:{imgUrl:imgUrl}}));
    })

    // /**将请求参数传入，multiparty会进行相应处理*/
    // form.parse(req)
    // /**接收到数据参数时，触发field事件*/
    // form.on('field', (name, value) => {
    //     console.log("------field---------",name, value)
    // })
    // /**接收到文件参数时，触发file事件*/
    // form.on('file', (name, file, ...rest) => {
    //     console.log("------file:---------",name, file)
    // })
    // /**表单数据解析完成，触发close事件*/
    // form.on('close', () => {
    //     console.log('--------表单数据解析完成-----------------')
    // })
})

class HomeController{

    async toHomePage(req,res,next){
        console.log("homeController ========== req.url:", req.url)
        // const {query:{category,page}} = req.url
        const options = {
            category:"最新文章"
        }
        const values = await services.getArticlesList(1,20,options)
        console.log("values:",values)
        res.render('blog/home.html',{title:"最新文章",articleList:values,info:info});
    }
}

const home = new HomeController()
module.exports = {router,home}


